package m.system.db;

import m.common.model.util.QueryParameter;
import m.system.util.StringUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * sql拼接
 */
public class SqlBuffer {
	private final Integer maxSeconds;
	private final StringBuffer sql=new StringBuffer();
	private final List<Object> paramList= new ArrayList<>();
	public SqlBuffer() {
		this.maxSeconds=DBConfig.getMaxConnect();
	}
	public SqlBuffer(int maxSeconds) {
		this.maxSeconds=maxSeconds;
	}
	public SqlBuffer append(String sqlPart) {
		if(StringUtil.isSpace(sqlPart)) return this;
		sql.append(sqlPart).append(" ");
		return this;
	}
	/**
	 * 添加sql片段
	 *  sqlPart
	 *  params
	 * 
	 */
	public SqlBuffer append(String sqlPart,Object... params) {
		if(StringUtil.isSpace(sqlPart)) return this;
		sql.append(sqlPart).append(" ");
		paramList.addAll(Arrays.asList(params));
		return this;
	}
	/**
	 * 返回sql参数
	 * 
	 */
	public QueryParameter toQueryParameter() {
		return new QueryParameter(sql.toString(),paramList);
	}
	/**
	 * 执行更新
	 * 
	 *  SQLException
	 */
	public int executeUpdate() throws SQLException {
		return DBManager.executeUpdate(sql.toString(), paramList.toArray(new Object[] {}),maxSeconds);
	}
	/**
	 * 执行查询
	 * 
	 *  SQLException
	 */
	public DataSet executeQuery() throws SQLException {
		return DBManager.executeQuery(sql.toString(), paramList.toArray(new Object[] {}),maxSeconds);
	}
	/**
	 * 执行查询第一行
	 * 
	 *  SQLException
	 */
	public DataRow queryFirstRow() throws SQLException {
		return DBManager.queryFirstRow(sql.toString(), paramList.toArray(new Object[] {}),maxSeconds);
	}
}
